package org.elec.mac.controller;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@Controller
public class IndexController {

    @Value("${tencent.wx.appid}")
    private String appid;

    @Value("${tencent.wx.authorize}")
    private String authorize;

    @Value("${tencent.wx.redirecturi}")
    private String redirect_uri;

    @RequestMapping(value = "/index.do")
    private void indexHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
        String user_agent = request.getHeader("User-Agent");
        String mach = request.getParameter("mach");
        if(user_agent.contains("AlipayClient")) {
            response.sendRedirect("");
        } else if(user_agent.contains("MicroMessenger")) {
            StringBuilder builder = new StringBuilder();
            builder.append(authorize);
            builder.append("?appid=").append(appid);
            builder.append("&redirect_uri=").append(URLEncoder.encode(redirect_uri, "UTF-8").toLowerCase());
            builder.append("&response_type=").append("code");
            builder.append("&scope=").append("snsapi_userinfo");
            builder.append("&state=").append(mach);
            builder.append("&connect_redirect=").append("1#wechat_redirect");
            response.sendRedirect(builder.toString());
        } else {
            response.sendRedirect("/refuse.html");
        }
    }

}